<template>
    <rx-layout>
        <template #middle>
            <div class="SysDicView" style="padding: 10px;width: 100%;height: 100%">
                <rx-fit>
                    <template #head>
                        <div>
                            <span style="margin-right: 10px;">【{{ $i18(sysTree.name) }}】
                                 {{ i18n('button.maintenance', '分类维护') }}
                            </span>
                            <a-space>
                                <a-button type="primary" @click="newRow">
                                    <PlusOutlined/>
                                    {{ i18n('button.itemAdd', '添加数据项') }}
                                </a-button>
                                <a-button type="primary" @click="saveItems">
                                    <SaveOutlined/>
                                    {{ i18n('button.itemSave', '保存数据项') }}
                                </a-button>
                                <a-button  type="primary" danger @click="delRow">
                                    <DeleteOutlined/>
                                    {{ i18n('button.itemDelete', '删除数据项') }}
                                </a-button>
                            </a-space>
                        </div>
                    </template>
                    <template #middle>
                        <rx-grid
                            :key="refresh"
                            ref="dicTable"
                            :hasPage="true"
                            :hasSeq="false"
                            :pageConfig="pageConfig"
                            :selectConfig="selectConfig"
                            :data="dicData"
                            field="dicId"
                            :columns="columns"
                            :treeConfig="treeConfig"
                        >
                            <template #name="{row,rowIndex}">
                                <RxLangInput @click.stop="" v-model="row.name"></RxLangInput>
                            </template>
                            <template #value="{row,rowIndex}">
                                <a-input @click.stop="" v-model:value="row.value"></a-input>
                            </template>
                            <template #descp="{row,rowIndex}">
                                <a-input @click.stop="" v-model:value="row.descp"></a-input>
                            </template>
                            <template #sn="{row,rowIndex}">
                                <a-input-number @click.stop="" v-model:value="row.sn" :min="1" style="width:100%;"/>
                            </template>
                            <template #colorConfigs="{row,rowIndex}">
                                <div @click.stop="" class="rx-colorConfigs">
                                    <div class="rx-colorConfigs-name">
                                    <span class="rx-colorConfigs-span" :style="styleName(row)">
                                        {{ getName(row.name) }}
                                    </span>
                                    <rx-icon-show v-if="styleShow(row)" @click="deleteStyle(row)" class="rx-colorConfigs-delete" size="16px" icon="iconicon-test28"></rx-icon-show>
                                    </div>
                                    <rx-icon-show class="colorConfigIcon" icon="icon-lineVue3_setting" @click="openConfig(row)"></rx-icon-show>
                                </div>
                            </template>
                            <template #action="{ row }">
                                <RxGridAction :size="2">
                                    <div @click="onSave(row)">{{ $ti18('rxForm.saveBtn', '保存') }}</div>
                                    <template v-if="dataShowType()!='FLAT' ">
                                        <div @click="onAddSibling(row)">{{ i18n('form.addSibling', '添加同级') }}</div>
                                        <div @click="addChildDic(row)">{{ i18n('form.addChild', '添加子级') }}</div>
                                    </template>
                                    <div @click="onDel(row)">{{ $ti18('rxList.delBtn', '删除') }}</div>
                                </RxGridAction>
                            </template>
                        </rx-grid>
                    </template>
                </rx-fit>
            </div>
        </template>
    </rx-layout>
</template>

<script>
/**
 * 数据字典
 */

import {RxLayout, RxLangInput, RxFit,Util} from '@lowcode/jpaas-base-lib'
import SysTreeApi from "@/common/api/system/sysTree.js";
import SysDicApi from "@/common/api/system/sysDic.js";
import SysDicColorConfig from "./SysDicColorConfig.vue";
import {App} from "@lowcode/jpaas-share-component"

export default {
    name: "SysDicView",
    components: {RxLayout, RxFit, RxLangInput},
    mixins:[App],
    props: {
        alias: {
            type: String
        },
        //这个是从DialogView打开时需要用到的。
        menuParams: {
            type: String
        },
    },
    data() {
        return {
            pageConfig:{
                pageSize:10,
                pageSizes:[10,30,40]
            },
            catKey: 'DIC',
            sysTree: {},
            curAlias: '',//当前数据字典别名
            columns: [
                {
                    title: this.i18n('form.itemName', '项名'),
                    field: 'name',
                    minWidth: 180,
                    slots: {default: 'name'},
                    treeNode:true
                },
                {
                    title: this.i18n('form.itemValue', '项值'),
                    field: 'value',
                    minWidth: 180,
                    slots: {default: 'value'},
                },
                {
                    title: this.i18n('form.itemDescription', '项描述'),
                    field: 'descp',
                    minWidth: 180,
                    slots: {default: 'descp'},
                },
                {
                    title: this.$ti18('rxList.index', '序号'),
                    field: 'sn',
                    minWidth: 180,
                    slots: {default: 'sn'},
                },
                {
                    title: this.i18n("form.StyliZe", "风格化"),
                    field: 'colorConfigs',
                    minWidth: 120,
                    allowCellEdit: false,
                    slots: {default: 'colorConfigs'},
                },
                {
                    title: this.$ti18('rxList.action', '操作'),
                    field: 'action',
                    minWidth: 120,
                    allowCellEdit: false,
                    slots: {default: 'action'},
                },
            ],
            selectConfig: {
                type: 'checkbox',
                checkStrictly:true
            },
            treeConfig:{},
            dicData:[],//数据字段数据
            refresh:'a'
        }
    },
    computed: {
        dicTable() {
            return this.$refs.dicTable;
        },
        language() {
            return window.localStorage.getItem('language') || 'zh-CN';
        },
    },
    mounted() {
        this.init();
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "sysDic", key);
        },
        async init() {
            //初始化别名。
            if (!this.alias) {
                //从dialogview 打开。
                if (this.menuParams) {
                    var json = JSON.parse(this.menuParams);
                    this.curAlias = json.alias;
                }
                //从路由打开。
                else {
                    let _params = this.$route.meta.params;
                    if (!_params) {
                        return;
                    }
                    let json = JSON.parse(_params);
                    this.curAlias = json.alias;
                }
            }
            let res = await SysTreeApi.getByAliasCatKey(this.curAlias, this.catKey);
            if (res.data) {
                this.sysTree = res.data;
                if(this.sysTree.dataShowType=="TREE"){
                    this.treeConfig={
                        transform:false,//平铺数据类型的时候，自动将列表转为树结构
                        children:'children',//指定子节点的属性名
                        rowField:'dicId',//节点的唯一值
                        parentField:'parentId',//父节点的唯一值
                    };
                }
                this.initTable();
            }
        },
        initTable() {
            SysDicApi.getByTreeId(this.sysTree.treeId).then(res=>{
                let data=res?res:[];
                let ary=Util.treeData(data,"dicId","parentId");
                this.dicData=ary;
                this.$refs.dicTable.loadData(ary);
            });
        },
        getName(name){
            return name ? (Util.isJson(name) ? JSON.parse(name)[this.language] : name) : "";
        },
        deleteStyle(record){
            record.colorConfigs="";
            this.onSave(record)
        },
        openConfig(record) {
            let config=record.colorConfigs
            if (record.colorConfigs && typeof record.colorConfigs =='string' ){
                config=JSON.parse(record.colorConfigs)
            }
            let conf= {
                curVm:this,
                data:{
                    config:config,
                    name:this.getName(record.name)
                },
                component:SysDicColorConfig,
                widthHeight: ['600px', '550px'],
                title: this.i18n("form.StyliZeConfig","风格化配置")
            };
            let self_=this;
            Util.open(conf,function(action,data){
                if (action!="ok"){
                    return
                }
                record.colorConfigs=data;
                self_.onSave(record)
            })
        },
        //风格化
        styleName(record) {
            if (!record.colorConfigs) {
                return
            }
            let style = JSON.parse(record.colorConfigs);
            return {
                background: style.bgcolor,
                color: style.fgcolor,
            };
        },
        saveItems() {
            let data = this.dicTable.getData();
            let show = this.needFillShoe(data)
            if(!show){ return}
            SysDicApi.batchSave({
                treeId: this.sysTree.treeId,
                gridData: JSON.stringify(data)
            }).then(res => {
                this.initTable();
            })
        },
        needFillShoe(data){
            let message = this.i18n('isMsg.needFill', '请填写项名和项值')
            for (let i = 0; i < data.length; i++) {
                let row = data[i];
                if(row.isAdd){
                    delete row.dicId;
                }
                if (!row.name || row.name===`{\"zh-CN\":\"\"}` || !row.value) {
                    this.$message.warn(message);
                    return false;
                }
                if(row.children && row.children.length){
                    let show =  this.needFillShoe(row.children);
                    if(show === false){
                        return false
                    }
                }
            }
            return true
        },
        getMaxSn(ary){
            let maxSn=1;
            if(ary && ary.length>0){
                let snAry=ary.map(item=>{
                    return item.sn;
                })
                maxSn=Math.max(...snAry);
                maxSn+=10;
            }
            return maxSn;
        },
        newRow() {
            let data = this.dicTable.getData()
            let maxSn=this.getMaxSn(data)
            let obj={dicId: Util.randomId(), isAdd: true, appId: this.curApp.appId,sn:maxSn};
            this.dicTable.addRow(obj);
        },
        delRow() {
            var rows = this.dicTable.getSelectedRows();
            if (rows.length == 0) {
                this.$message.error(this.i18n('isMsg.deleteData', '请选择删除的数据项！'));
                return;
            }
            let self_ = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips', '操作提示'),
                content: this.$ti18('rxMsa.delInfo', '您确定需要删除选中的记录吗？'),
                okText: this.$ti18('rxForm.ackBtn', '确认'),
                cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                onOk() {
                  var ids = [];
                  for (var i = 0; i < rows.length; i++) {
                    if (!rows[i].isAdd) {
                      ids.push(rows[i].dicId);
                    }
                  }
                  self_.dicTable.removeRows(rows.map(item=>{
                    return item.dicId;
                  }));
                  if(ids.length==0){
                    return;
                  }
                    SysDicApi.delByDicIds(ids.join(','), self_.sysTree.treeId).then(res => {
                        self_.initTable();
                    })
                },
                onCancel() {
                }
            })
        },
        onDel(record) {
            let self_ = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips', '操作提示'),
                content: this.$ti18('rxMsa.delInfo', '您确定需要删除选中的记录吗？'),
                okText: this.$ti18('rxForm.ackBtn', '确认'),
                cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                onOk() {
                  if (record.isAdd) {
                    self_.dicTable.removeRows([record.dicId]);
                    return;
                  }
                    SysDicApi.delByDicIds(record.dicId, self_.sysTree.treeId).then(res => {
                        self_.initTable();
                    })
                },
                onCancel() {
                }
            })
        },
        onSave(record) {
            let self_ = this;
            let message = this.i18n('isMsg.needFill', '请填写项名和项值');
            if (!record.name || record.name===`{\"zh-CN\":\"\"}` || !record.value) {
                this.$message.warn(message);
                return;
            }
            if(record.isAdd){
                delete record.dicId;
            }
            SysDicApi.rowSave({treeId: this.sysTree.treeId, data: JSON.stringify(record)}).then(res => {
                self_.initTable();
            })
        },
        onAddSibling(record) {
            if (record.parentId && record.parentId != '0') {
                this.dicTable.addRow({dicId: Util.randomId(), isAdd: true,sn: 1,parentId: record.parentId});
            } else {
                this.dicTable.addRow({dicId: Util.randomId(), isAdd: true,sn: 1,});
            }
        },
        /**
         * 获取要展开的行
         * @param row 当前行
         * @param xTable
         * @returns {*[]}
         */
        expandRow(row,xTable){
            let _row = row ,rows = [];
            while (_row && _row['dicId']){
                rows.push(_row)
                if(_row.parentId){
                    _row = xTable.getRowById(_row.parentId)
                }else {
                    _row = ''
                }
            }
            return rows.reverse();
        },
        /**
         * 设置展开行
         * @param row
         */
        refreshData(row){
            let xTable =this.$refs.dicTable.RxGrid || this.$refs.dicTable.$refs['xTable'];
            if(xTable){
                xTable.$nextTick().then(()=>{
                    let rows = this.expandRow(row,xTable);
                    for (let item of rows){
                        xTable.setTreeExpand(item,true)
                    }
                })
            }
        },
        addChildDic(record) {
            if(!record.children){
                record.children=[];
            }
            record.children.push({dicId: Util.randomId(), isAdd: true,sn: 1, parentId: record['dicId']})
            this.$nextTick(()=>{
                this.refreshData(record)
            })
        },
        dataShowType() {
            return this.sysTree.dataShowType || "FLAT";
        },
        styleShow(record){
            if(!record.colorConfigs){
                return false
            }
            let style = JSON.parse(record.colorConfigs);
            if(style.bgcolor || style.fgcolor){
                return true
            }
            return  false
        }
    },
    watch: {
        "$route": {
            handler: function (o, ol) {
                this.init();
            },
            deep: true
        }
    }
}
</script>

<style scoped>
.rx-colorConfigs {
    display: flex;
    height: 30px;
    align-items: center;
    width: 100%;
    border: 1px solid #dadde0;
    border-radius: 5px;
}

.rx-colorConfigs-name {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    height: 30px;
    display: flex;
    align-items: center;
    border-right: 1px solid #dadde0;
    padding-left: 5px;
}

.rx-colorConfigs-span{
    padding: 0px 8px;
    height: 20px;
    line-height: 20px;
    border-radius: 3px;
    font-size: 12px;
    flex: 1;
    margin-right: 5px;
}

.colorConfigIcon {
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

.colorConfigIcon:hover {
    color: #2387fa;
}
.SysDicView>>>.vxe-body--column:before{
    display: none;
}
.rx-colorConfigs-name:hover .rx-colorConfigs-delete{
    display: block;
    color: #f66767;
    cursor: pointer;
}
.rx-colorConfigs-delete{
    font-size: 16px;
    display: none;
    margin-right: 5px;
}
</style>
